package com.yzt.minemodule;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Build;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.yzt.minemodule.wallet.UserAuthActivity;
import com.yzt.p_base.utils.ToastUtil;
import com.yzt.zhuju.RXingUtils;
import com.yzt.zhuju.arouter.RouterMain;
import com.yzt.zhuju.arouter.RouterMine;
import com.yzt.zhuju.arouter.RouterUser;
import com.yzt.zhuju.base.BaseFragment;
import com.yzt.zhuju.network.AresSubscriber;
import com.yzt.zhuju.network.biz.BizLayer;
import com.yzt.zhuju.network.entity.mine.wallet.WalletConfigBean;
import com.yzt.zhuju.network.entity.user.PersonalDetailBasic;
import com.yzt.zhuju.photoview.PhotoViewManager;
import com.yzt.zhuju.utils.PersonalDetailCacheManager;
import com.yzt.zhuju.voice.VoicePlayManager;
import com.yzt.zhuju.widget.PageIndicatorView;
import com.yzt.zhuju.widget.tuiview.TUITextView;
import com.yzt.zhuju.widget.widget.ImageLoadManger;
import com.yzt.minemodule.activity.MineOrderActivity;
import com.yzt.minemodule.activity.SettingActivity;
import com.yzt.minemodule.activity.SkillActivity;
import com.yzt.minemodule.banner.BannerViewHolder;
import com.yzt.minemodule.fragment.UserActivityFragment;
import com.yzt.minemodule.fragment.UserDynamicFragment;
import com.yzt.minemodule.wallet.WalletActivity;
import com.yzt.p_base.AppUtils;
import com.yzt.plugin_imageloader.ImageLoadUtil;
import com.yzt.plugin_widget.RoundImageView;
import com.yzt.plugin_widget.tableBar.SlidingTabLayout;
import com.yzt.plugin_widget.viewPager.ViewPagerAdapter;
import com.zhouwei.mzbanner.MZBannerView;
import com.zhouwei.mzbanner.holder.MZHolderCreator;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.jzvd.Jzvd;

/**
 * author : bob
 * date   : 2022/12/1
 * desc   : 我的模块
 */
@SuppressLint("SetTextI18n")
@Route(path = RouterMine.FRAGMENT_MINE)
public class MineFragment extends BaseFragment {

    /**
     * 轮播图
     */
    private MZBannerView<String> bannerView;
    private PageIndicatorView indicatorView;

    private PhotoViewManager photoViewManager;

    private final List<String> albums = new ArrayList<>();

    private PersonalDetailBasic mPersonalDetail;

    private RelativeLayout rlContainer;

    private RoundImageView imgAvatar;
    private TextView mTvName;
    private TextView followCount;
    private TextView fansCount;
    private TextView friendCount;
    private TextView likeCount;

    private TUITextView tv_gender;
    private TUITextView tv_constellation;
    private TextView tvDesc;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_mine;
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void installViews() {

        photoViewManager = PhotoViewManager.getInstance(AppUtils.getApp());

        // 昵称 在线 id
        mTvName = findViewById(R.id.tvPersonName);
        imgAvatar = findViewById(R.id.img_header);
        imgAvatar.setOnClickListener(this);
        followCount = findViewById(R.id.tv_follow_count);
        fansCount = findViewById(R.id.tv_fans_count);
        friendCount = findViewById(R.id.tv_friend_count);
        findViewById(R.id.tv_follow_count1).setOnClickListener(this);
        findViewById(R.id.tv_fans_count1).setOnClickListener(this);
        findViewById(R.id.tv_friend_count1).setOnClickListener(this);
        followCount.setOnClickListener(this);
        fansCount.setOnClickListener(this);
        friendCount.setOnClickListener(this);

        likeCount = findViewById(R.id.tv_like_count);

        tv_gender = findViewById(R.id.tv_gender);
        tv_constellation = findViewById(R.id.tv_constellation);

        // 签名
        tvDesc = findViewById(R.id.tv_user_desc);

        findViewById(R.id.img_set).setOnClickListener(this);
        rlContainer = findViewById(R.id.rl_set_more);
        rlContainer.setOnClickListener(this);
        findViewById(R.id.tv_account).setOnClickListener(this);
        findViewById(R.id.tv_help).setOnClickListener(this);
        findViewById(R.id.tv_order).setOnClickListener(this);
        findViewById(R.id.tv_skill).setOnClickListener(this);
        findViewById(R.id.tv_set).setOnClickListener(this);
        findViewById(R.id.tv_auth).setOnClickListener(this);
        findViewById(R.id.tv_edit_info).setOnClickListener(this);
        findViewById(R.id.tv_mine_wallet).setOnClickListener(this);

        // 初始轮播图
        initBannerView();

        // 缓存数据
        getHttpData();

        // 加载视图
        initViews();
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);

        if (view.getId() == R.id.img_set) {
            rlContainer.setVisibility(View.VISIBLE);
        }
        if (view.getId() == R.id.rl_set_more) {
            rlContainer.setVisibility(View.GONE);
        }
        if (view.getId() == R.id.tv_account) {
            rlContainer.setVisibility(View.GONE);
            RouterMine.AccountSecurityActivity();
        }
        if (view.getId() == R.id.tv_help) {
            rlContainer.setVisibility(View.GONE);
            RouterMain.goToWeb(getString(R.string.privacy_policy_url));
        }
        if (view.getId() == R.id.tv_order) {
            rlContainer.setVisibility(View.GONE);
            Intent in = new Intent(getContext(), MineOrderActivity.class);
            startActivity(in);
        }
        if (view.getId() == R.id.tv_skill) {
            rlContainer.setVisibility(View.GONE);
            Intent in = new Intent(getContext(), SkillActivity.class);
            startActivity(in);
        }
        if (view.getId() == R.id.tv_set) {
            rlContainer.setVisibility(View.GONE);
            SettingActivity.start(getActivity());
        }
        if (view.getId() == R.id.tv_auth) {
            userAuth();
            rlContainer.setVisibility(View.GONE);
        }
        if (view.getId() == R.id.tv_edit_info) {
            RouterUser.PersonDetailEditActivity(RXingUtils.getUserId());
        }
        if (view.getId() == R.id.tv_mine_wallet) {
            Intent intent = new Intent(getContext(), WalletActivity.class);
            startActivity(intent);
        }
        if (view.getId() == R.id.tv_follow_count1 || view.getId() == R.id.tv_follow_count) {
            RouterUser.FriendListActivity(RouterUser.FriendType.TYPE_FOLLOW, RXingUtils.getPersonDetail().getBasic().getUserId());
        }
        if (view.getId() == R.id.tv_fans_count1 || view.getId() == R.id.tv_fans_count) {
            RouterUser.FriendListActivity(RouterUser.FriendType.TYPE_FANS, RXingUtils.getPersonDetail().getBasic().getUserId());
        }
        if (view.getId() == R.id.tv_friend_count1 || view.getId() == R.id.tv_friend_count) {
            RouterUser.FriendListActivity(RouterUser.FriendType.TYPE_FRIEND, RXingUtils.getPersonDetail().getBasic().getUserId());
        }
    }

    /**
     * 实名认证
     */
    public void userAuth() {
        BizLayer.getInstance().getMineModule().walletConfig(new AresSubscriber<WalletConfigBean>() {
            @Override
            protected void onSuccess(WalletConfigBean wallet) {
                if (wallet.isAuthed()) {
                    Intent intent = new Intent(mActivity, UserAuthActivity.class);
                    startActivity(intent);
                } else {
                    ToastUtil.showMessage("你已经实名认证了～");
                }
            }
        });
    }

    @Override
    public void netWorkRequest() {

    }

    /**
     * 加载页面分类
     */
    private void initViews() {
        SlidingTabLayout mTabLayout = findViewById(R.id.tablayout);
        ViewPager mViewPager = findViewById(R.id.viewPager);
        List<String> tabs = new ArrayList<>();
        List<Fragment> fragments = new ArrayList<>();
        tabs.add("活动");
        tabs.add("动态");
        fragments.add(UserActivityFragment.getInstance(RXingUtils.getUserId()));
        fragments.add(UserDynamicFragment.getInstance(RXingUtils.getUserId()));
        mViewPager.setAdapter(new ViewPagerAdapter(getChildFragmentManager(), fragments, tabs));
        mViewPager.setOffscreenPageLimit(tabs.size());
        mTabLayout.setViewPager(mViewPager);
    }

    /**
     * banner栏
     */
    private void initBannerView() {
        indicatorView = findViewById(R.id.indicator);
        bannerView = findViewById(R.id.banner_view);
        bannerView.setIndicatorRes(R.drawable.shape_indicator_selected, R.drawable.shape_indicator_normal);
        bannerView.setIndicatorAlign(MZBannerView.IndicatorAlign.CENTER);
        bannerView.setBannerPageClickListener((view, position) -> {
            if (albums.size() == 0) {
                return;
            }
            List<String> list = new ArrayList<>();
            List<String> newList = new ArrayList<>(albums);
            for (String album : newList) {
                list.add(ImageLoadUtil.url2Webp(album));
            }
            newList.clear();
            photoViewManager.showPhotoView(view, list, position);
        });

        bannerView.addPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                indicatorView.setPersonalSelectedPage(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        initAlbum();
    }

    /**
     * 获取页面数据
     * 缓存数据 - 网络请求
     */
    public void getHttpData() {
        // 用户信息
        Map<String, String> map = new HashMap<>();
        map.put("userId", RXingUtils.getUserId());
        BizLayer.getInstance().getAccountModule().getFullInfoParts(map, new AresSubscriber<PersonalDetailBasic>() {
            @Override
            protected void onSuccess(PersonalDetailBasic personalDetail) {
                PersonalDetailCacheManager.addPersonalDetail(personalDetail);
                mPersonalDetail = personalDetail;
                try {
                    initData();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 加载相册
     */
    private void initAlbum() {
        indicatorView.setVisibility(albums.size() > 1 ? View.VISIBLE : View.GONE);
        indicatorView.initPersonalIndicator(albums.size());
        bannerView.setIndicatorVisible(false);
        bannerView.setPages(albums, (MZHolderCreator<BannerViewHolder>) BannerViewHolder::new);
        bannerView.setCanLoop(false);
    }

    /**
     * 加载用户信息
     */
    public void initData() {

        if (mPersonalDetail.getBgImage() != null) {
            albums.add(mPersonalDetail.getBgImage());
        }
//        else {
//            albums.add(mPersonalDetail.getAvatar());
//        }
        initAlbum();

        // 头像
        ImageLoadManger.loadIv(mActivity, mPersonalDetail.getAvatar(), imgAvatar, R.mipmap.default_photo);

        // 昵称
        mTvName.setText(mPersonalDetail.getNickName());

        // 粉丝
        followCount.setText(String.valueOf(mPersonalDetail.getFollowNum()));
        fansCount.setText(String.valueOf(mPersonalDetail.getFansNum()));
        friendCount.setText(String.valueOf(mPersonalDetail.getFriendNum()));
        likeCount.setText(String.valueOf(mPersonalDetail.getLikeNum()));

        // 年龄
        tv_gender.setSelected(mPersonalDetail.getGender() == 1);
        tv_gender.setText(mPersonalDetail.getAge() + "岁");

        // 星座
        tv_constellation.setText(mPersonalDetail.getConstellation());

        // 自我介绍
        if (mPersonalDetail.getIntro() == null || mPersonalDetail.getIntro().equals("")) {
            tvDesc.setText("这个人很懒，什么都没有留下");
        } else {
            tvDesc.setText(mPersonalDetail.getIntro());
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        Jzvd.goOnPlayOnPause();
        VoicePlayManager.getInstance().stopPlay();
    }

    @Override
    public void onResume() {
        super.onResume();
        getHttpData();
    }
}